import { useUserStore } from '@/store/user.js'
import request from '@/utils/request'

export const requestInterceptor = (config) => {
  const header = {
    'Content-Type': 'application/json',
    ...config.header
  }
  const userStore = useUserStore()
  const accessToken = userStore.accessToken
  if (accessToken) {
    header['token'] = accessToken
  }
  return {
    ...config,
    header
  }
}

export const responseInterceptor = (response) => {
  if (response.statusCode === 200) {
    if (response.data.code !== '0') {
      // token失效处理 - 直接抛出错误，由上层统一处理
      if (response.data.code === '8001') {
        uni.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none'
        })
        throw response
      }
      uni.showToast({
        title: response.data.message || '请求失败',
        icon: 'none'
      })
      throw response.data
    }
    return response.data
  } else {
    uni.showToast({
      title: response.data.message || '请求失败',
      icon: 'none'
    })
    throw response
  }
}

export const errorInterceptor = (error) => {
  uni.showToast({
    title: '网络错误，请检查网络连接',
    icon: 'none'
  })
  return Promise.reject(error)
}